<template>
    <div class="sdy-search">
    <SdyHeader title="啥都有" back>
        
        <template #title>
            <van-search v-model="searchText" shape="round" background="#c72418" placeholder="请输入搜索关键词" />
        </template>
        <template #right>
            
            <van-button @click="sreachHandler" size="small" type="success">搜索</van-button>
        </template>
    </SdyHeader>
    
    <!-- 搜索相关的内容显示 -->
    <!--如果searchText没有文本显示-->
    <!-- <SdySearchHistory v-if="!searchText"></SdySearchHistory> -->
    <!--如果searchText有文本显示-->
    <!-- <SdySearchList v-else></SdySearchList> -->

    <!--当searchText为true的时候渲染SdySearchList组件-->
    <!--当searchText为false的时候渲染SdySearchHistory组件-->
    <component :is="searchText ? SdySearchList : SdySearchHistory"></component>


    </div>
</template>

<script setup lang="ts">
import SdySearchHistory from './components/SdySearchHistory.vue'
import SdySearchList from './components/SdySearchList.vue';
import { ref, watch, provide } from 'vue'
import { useRouter, type Router } from 'vue-router'

//倒入相关api请求借口
import { searchListApi } from '@/api/goods'

//导入相关 ts 接口
import type { MyHotItem  } from '@/config/interface';

const $router: Router = useRouter()


//准备一个数据，和文本框交互
const searchText = ref<string>('')

//准备一个点击搜索按钮的方法
const sreachHandler = () => {
    // console.log(searchText.value)
    const text = searchText.value.trim()
    //非空验证
    if (!text) return

    //跳转路由
    $router.push({ path: '/list', query: { search: text} })
}

//随着搜索的关键字变化实时请求最新的相关数据展示
//准备一个数据，表示搜索列表
const searchList = ref<MyHotItem[]>([])

// 利用 watch 监控 searchText
watch(searchText, async () => {
    if (!searchText.value.trim()) return
    const res = await searchListApi(searchText.value.trim())
    searchList.value = res.data
})

provide('searchList', searchList)
</script>

<style setup lang="scss"></style>